// 导入逆地址解析sdk
import QQMapWX from '@/libs/qqmap-wx-jssdk.min'
// 导入验证函数
import Schema from 'async-validator'
import { reqAddOrUpdateAddress, reqAddressDetail } from '@/api/address'

Page({
  // 页面的初始数据
  data: {
    name: '',
    phone: '',
    provinceName: '',
    provinceCode: '',
    cityName: '',
    cityCode: '',
    districtName: '',
    districtCode: '',
    address: '', //详细地址
    fullAddress: '', //完整地址
    isDefault: false //设为默认地址
  },

  // 生命周期函数--监听页面加载
  onLoad: function (options) {
    const { id } = options
    // 有接收到传过来的id才set到data
    if (id) {
      this.setData({
        id
      })
      // 设置页面标题
      wx.setNavigationBarTitle({
        title: '修改收货地址'
      })
      this.getAddressDetail()
    }
    // 实例化sdk，挂载到this
    this.qqMapSdk = new QQMapWX({
      key: 'S3KBZ-A6ZWZ-5VOXW-ZIFER-JHN2S-K6FEA' // 申请的应用的key
    })
  },

  selectedRegion(e) {
    const [provinceName, cityName, districtName] = e.detail.value
    const [provinceCode, cityCode, districtCode] = e.detail.code
    this.setData({
      provinceName,
      provinceCode,
      cityName,
      cityCode,
      districtName,
      districtCode
    })
  },

  // 定位
  async handleChooseLocation() {
    // wx.chooseLocation返回结果不包含省市区编码code，因此需要用到逆地址解析
    const { latitude, longitude } = await wx.chooseLocation()
    this.qqMapSdk.reverseGeocoder({
      location: {
        latitude,
        longitude
      },
      success: (res) => {
        // 收集省市区编码code
        const { adcode, province, city, district } = res.result.ad_info
        // 位置name
        const { title } = res.result.address_reference.landmark_l2
        // 详细地址：街道、门牌
        const { street, street_number } = res.result.address_component
        this.setData({
          provinceName: province,
          provinceCode: adcode.replace(adcode.substring(2), '0000'),
          cityName: city,
          cityCode: adcode.replace(adcode.substring(4), '00'),
          districtName: district,
          districtCode: district && adcode, //有些市下面无区级
          address: `${street}${street_number}`,
          fullAddress: `${province}${city}${district}${street}${street_number}(${title})`
        })
      },
      fail: (err) => {
        wx.toast({ title: err.message })
      }
    })
  },

  // 保存
  async saveAddressBtn() {
    const { provinceName, cityName, districtName, address, isDefault } = this.data
    const params = {
      ...this.data,
      fullAddress: provinceName + cityName + districtName + address,
      isDefault: isDefault ? 1 : 0
    }
    const validateRes = await this.validateAddress(params)
    // 验证不通过就返回
    if (!validateRes) return
    const res = await reqAddOrUpdateAddress(params)
    if (res.code === 200) {
      const { id } = this.data
      // 为避免点击更新按钮后页面直接跳转上一页而没有出现toast
      // 将toast放到success中
      wx.navigateBack({
        success: () => {
          wx.toast({ title: id ? '修改收货地址成功' : '新增收货地址成功' })
        }
      })
    } else {
      wx.toast({ title: id ? '修改收货地址失败' : '新增收货地址失败' })
    }
  },
  // 定义验证规则
  validateAddress(data) {
    // 姓名
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
    // 手机号
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    const rules = {
      name: [
        { required: true, message: '请输入收货人姓名' },
        { pattern: nameRegExp, message: '收货人姓名不合法' }
      ],
      phone: [
        { required: true, message: '请输入收货人手机号' },
        { pattern: phoneReg, message: '手机号不合法' }
      ],
      provinceName: [{ required: true, message: '请选择地区' }],
      address: [{ required: true, message: '请输入详细地址' }]
    }
    // 创建实例，传入验证规则
    const validator = new Schema(rules)
    // 验证，返回个promise函数
    return new Promise((resolve) => {
      validator.validate(data, (errors) => {
        // errors为null则验证成功
        if (errors) {
          wx.toast({ title: errors[0].message })
          resolve(false)
        } else {
          resolve(true)
        }
      })
    })
  },
  // 详情
  async getAddressDetail() {
    const res = await reqAddressDetail(this.data.id)
    if (res.code === 200) {
      const detail = res.data
      this.setData({
        ...detail
      })
    }
  }
})
